package com.ys.service.business.impl;

import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpAnalysisDailyTarget;
import com.ys.entity.business.TpAnalysisDailyTargetSet;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.business.TpAnalysisDailyTargetMapper;
import com.ys.service.business.TpAnalysisDailyTargetService;
import com.ys.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service("tpAnalysisDailyTargetService")
public class TpAnalysisDailyTargetServiceImpl implements TpAnalysisDailyTargetService {

	@Autowired
	private TpAnalysisDailyTargetMapper tpAnalysisDailyTargetMapper;

	@Autowired
	private DiySqlMapper diySqlMapper;


	@Override
	public int addByDay(String agoDay) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		Date oldDate = null;
		try {
			oldDate = sdf.parse(agoDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		calendar.setTime(oldDate);
		SimpleDateFormat sdfYM = new SimpleDateFormat("yyyy-MM");
		String agoDayMonth = sdfYM.format(calendar.getTime());//昨天的月份

		int dayCount = new DateUtil().getMonthLastDay(agoDayMonth);//获取月份的最后一天

		//获取所有运营公司数据
		List<ThrOperateCompanyApply> companyList = new ThrOperateCompanyApply().queryList();
		if(companyList!=null && companyList.size()>0){

			//根据月份查询设置数据
			List<TpAnalysisDailyTargetSet> targeSetListByMonth = new TpAnalysisDailyTargetSet().where("A.InfoTime = '"+agoDayMonth+"'").queryList();
			//统计查询昨天的商品订单数据

			List<Map<String, Object>> oldDayOrderList = diySqlMapper.searchOldMonthAllOrderList(agoDay,agoDay);
			//统计查询昨天的月份的累计商品订单数据

			List<Map<String, Object>> oldDayOrderTotal =diySqlMapper.searchOldMonthAllOrderList(agoDayMonth+"-01",agoDay);
			//统计查询昨天和前天的精品订单数据
			List<Map<String, Object>> oldDayElaborateOrderList = diySqlMapper.searchOldMonthElaborateOrderList(agoDay,agoDay);
			//统计查询昨天的月份的累计精品订单数据
			List<Map<String, Object>> oldDayElaborateOrderTotal = diySqlMapper.searchOldMonthElaborateOrderList(agoDayMonth+"-01",agoDay);


			String vGsBms = null;
			for( ThrOperateCompanyApply thrOperateCompanyApply:companyList ){
				if(thrOperateCompanyApply.getVgsbm()!=null && !thrOperateCompanyApply.getVgsbm().equals("")){
					if(vGsBms == null || vGsBms.equals("")){
						vGsBms = "'"+ thrOperateCompanyApply.getVgsbm() + "'";
					}else {
						vGsBms = vGsBms + ",'"+ thrOperateCompanyApply.getVgsbm() + "'";
					}
				}
			}
			List<Map<String, Object>> tpAmazonShopList = new TpAmazonShop()
					.addField("O.VGsJc AS vGsJc")//运营公司简称
					.addField("PO.VGsJc AS pVGsJc")//上级运营公司简称
					.addField("C.UserId AS cUser ")//运营人工号
					.addField("C.UserName AS cUserName ")//运营人姓名
					.addField("C.DeptName AS cDeptName")//运营组别，所属部门
					.addField("PC.UserId AS pCUser ")//上级运营人工号
					.addField("PC.UserName AS pCUserName ")//上级运营人姓名
					.addField("PC.DeptName AS pCDeptName ")//运营组别上级，所属部门上级
					.addField("ORG.Name AS orgName")//机构名称
					//.addField("A.ShopName AS shopName ")//店铺名称
					.addField("S.RegionName AS regionName ")//店铺区域；
					//.addField("A.FirstSaleDay AS firstSaleDay ")//开售日期
					.addField("S.Vgsbm AS vgsbm")//
					.addLeftJoin("TP_AmazonSeller S ON S.id = A.amazonSellerId ")
					//关联运营公司备案表
					.addLeftJoin("THR_OperateCompanyApply O ON O.VGsBm = S.Vgsbm ")
					.addLeftJoin("TS_UserChange C ON C.Id = O.OperatorChangeId AND 1=1")
					//关联运营公司备案表-上级
					.addLeftJoin("TS_OperateOrg ORG ON ORG.Id = O.OperateOrgId ")
					.addLeftJoin("THR_OperateCompanyApply PO ON ORG.HeadVgsbm = PO.Vgsbm  AND 1=1")
					.addLeftJoin("TS_UserChange PC ON PC.Id = PO.OperatorChangeId  AND 1=1")
					//.addLeftJoin("THR_OperateCompanyRoute R ON R.VGsBm = A.CompanyID")

					.where("S.Vgsbm IN ( "+ vGsBms +" ) AND O.OperationsStatus !=4")
					.setOrderby("A.FirstSaleDay DESC")
					.queryMap();


			//删除数据
			diySqlMapper.delTpAnalysisDailyTargetByInfoTime(agoDay);

			List<TpAnalysisDailyTarget> entityList = new ArrayList<>();
			List<TpAnalysisDailyTarget> entityElaborateList = new ArrayList<>();

			//循环处理数据，并新增
			for(ThrOperateCompanyApply companyItem :companyList){
				String vGsBm = companyItem.getVgsbm();
				//新增普通订单
				TpAnalysisDailyTarget entity = setEntityByType(vGsBm,0,dayCount,agoDay,targeSetListByMonth,oldDayOrderList,oldDayElaborateOrderList,oldDayOrderTotal,oldDayElaborateOrderTotal,tpAmazonShopList);
				if(entity!=null){
					entityList.add(entity);
				}
				//新增精品订单
				TpAnalysisDailyTarget entityElaborate = setEntityByType(vGsBm,1,dayCount,agoDay,targeSetListByMonth,oldDayOrderList,oldDayElaborateOrderList,oldDayOrderTotal,oldDayElaborateOrderTotal,tpAmazonShopList);
				if(entityElaborate!=null){
					entityElaborateList.add(entityElaborate);
				}

			}
			//分批插入,一次插入50
			if(entityList!=null && entityList.size()>0){
				for(int i=0;i<entityList.size()+50;i=i+50){
					List<TpAnalysisDailyTarget> newlist = entityList.stream().skip(i).limit(50).collect(Collectors.toList());
					diySqlMapper.insertTpAnalysisDailyTarget(newlist);
				}
			}
			if(entityElaborateList!=null && entityElaborateList.size()>0){
				for(int i=0;i<entityElaborateList.size()+50;i=i+50){
					List<TpAnalysisDailyTarget> newlistElaborate = entityElaborateList.stream().skip(i).limit(50).collect(Collectors.toList());
					diySqlMapper.insertTpAnalysisDailyTarget(newlistElaborate);
				}
			}

		}
		return 1;
	}


	public TpAnalysisDailyTarget setEntityByType( String vGsBm,int addType,int dayCount,String agoDay,
												  List<TpAnalysisDailyTargetSet> targeSetListByMonth,
												  List<Map<String, Object>> oldDayOrderList,
												  List<Map<String, Object>> oldDayElaborateOrderList,
												  List<Map<String, Object>> oldDayOrderTotal,
												  List<Map<String, Object>> oldDayElaborateOrderTotal,
                                                  List<Map<String, Object>> tpAmazonShopList){
		Predicate<List> listIsNull = listInfo-> listInfo!=null && listInfo.size()>0;
		TpAnalysisDailyTarget entity = new TpAnalysisDailyTarget();
		entity.setStatus(0);
		int dailyTarget = 0;//上个月日目标
		int elaborateDailyTarget = 0;//上个月日目标-精品
		//日目标设置id
		if(targeSetListByMonth!=null && targeSetListByMonth.size()>0){
			List<TpAnalysisDailyTargetSet> infoListByShop = targeSetListByMonth.stream()
					.filter(item->item.getVGsBm().equals(vGsBm))
					.collect(Collectors.toList());
			if(infoListByShop.size()>0){
				long setId = infoListByShop.get(0).getId();
				dailyTarget = infoListByShop.get(0).getDailyTarget();//上个月日目标
				elaborateDailyTarget = infoListByShop.get(0).getElaborateDailyTarget();//上个月日目标-精品
				entity.setTargetSetId(setId);
			}
		}

		int todayOrder = 0;//当日订单数
		BigDecimal todayAmount = BigDecimal.ZERO;//当日订单金额
		BigDecimal todayAmountLocal = BigDecimal.ZERO;//当日订单金额(原货币)
		if(addType==0){//全部订单
			if(listIsNull.test(oldDayOrderList)){
				List<Map<String, Object>> infoListByShop = oldDayOrderList.stream()
						.filter(item->item.get("VGsBm").toString().equals(vGsBm))
						.collect(Collectors.toList());
				if(infoListByShop.size()>0){
					todayOrder = (int)infoListByShop.get(0).get("Num");
					todayAmount = (BigDecimal)infoListByShop.get(0).get("Amount");
					todayAmountLocal = (BigDecimal)infoListByShop.get(0).get("amountLocal");
				}
			}
		}else {//精品订单
			if(listIsNull.test(oldDayElaborateOrderList)){
				List<Map<String, Object>> infoListByShop = oldDayElaborateOrderList.stream().filter(item->item.get("VGsBm").toString().equals(vGsBm)).collect(Collectors.toList());
				if(infoListByShop.size()>0){
					todayOrder = (int)infoListByShop.get(0).get("Num");
					todayAmount = (BigDecimal)infoListByShop.get(0).get("Amount");
					todayAmountLocal = (BigDecimal)infoListByShop.get(0).get("amountLocal");
				}
			}
		}

		int accumulateOrder = 0;//当月累计订单

		BigDecimal accumulateAmount = BigDecimal.ZERO;//当月累计订单金额
		BigDecimal todayAmountLocallateAmount = BigDecimal.ZERO;//当月累计订单金额(原货币)
		//日增长率
		BigDecimal growthRate =  new BigDecimal("0");

		if(addType==0){//全部订单
			if(listIsNull.test(oldDayOrderTotal)){
				List<Map<String, Object>> infoListByShop = oldDayOrderTotal.stream().filter(item->item.get("VGsBm").toString().equals(vGsBm)).collect(Collectors.toList());
				if(infoListByShop.size()>0){
					accumulateOrder = (int)infoListByShop.get(0).get("Num");
					accumulateAmount = (BigDecimal)infoListByShop.get(0).get("Amount");
					todayAmountLocallateAmount = (BigDecimal)infoListByShop.get(0).get("amountLocal");
					//获取月目标总数
					BigDecimal monthTotal = new BigDecimal(dayCount).multiply(new BigDecimal(dailyTarget));//月天数*日目标
					//计算增长率
					BigDecimal oldData = new BigDecimal(accumulateOrder);
					growthRate =  (BigDecimal.ZERO).compareTo(monthTotal) == 0 ? new BigDecimal("1"):oldData.divide(monthTotal,4,BigDecimal.ROUND_HALF_UP);
				}
			}
		}else {//精品订单
			if(listIsNull.test(oldDayElaborateOrderTotal)){
				List<Map<String, Object>> infoListByShop = oldDayElaborateOrderTotal.stream().filter(item->item.get("VGsBm").toString().equals(vGsBm)).collect(Collectors.toList());
				if(infoListByShop.size()>0){
					accumulateOrder = (int)infoListByShop.get(0).get("Num");
					accumulateAmount = (BigDecimal)infoListByShop.get(0).get("Amount");
					todayAmountLocallateAmount = (BigDecimal)infoListByShop.get(0).get("amountLocal");
					//获取月目标总数
					BigDecimal monthTotal = new BigDecimal(dayCount).multiply(new BigDecimal(elaborateDailyTarget));//月天数*日目标
					//计算增长率
					BigDecimal oldData = new BigDecimal(accumulateOrder);
					growthRate =  (BigDecimal.ZERO).compareTo(monthTotal) == 0 ? new BigDecimal("1"):oldData.divide(monthTotal,4,BigDecimal.ROUND_HALF_UP);
				}
			}
		}

		//时间进度
		BigDecimal thisDay = new BigDecimal(agoDay.substring(agoDay.length()-2));
		BigDecimal dayCountNum = new BigDecimal(dayCount);
		BigDecimal timeSchedule = thisDay.divide(dayCountNum,4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));


		//过滤累计订单为0的数据
		if(accumulateOrder==0){
			return null;
		}

		//基础信息
        List<Map<String, Object>> tpAmazonShopListByGuid = tpAmazonShopList.stream()
				.filter(item -> item.get("vgsbm").equals(vGsBm))
				.collect(Collectors.toList());
        if(tpAmazonShopListByGuid.size()>0){
            Map<String, Object> item = tpAmazonShopListByGuid.get(0);
            entity.setVGsJc(item.get("vGsJc")!=null?item.get("vGsJc").toString():null);//运营公司简称
            entity.setPVGsJc(item.get("pVGsJc")!=null?item.get("pVGsJc").toString():null);//上级运营公司简称
            entity.setCUser(item.get("cUser")!=null?item.get("cUser").toString():null);//运营人工号
            entity.setCUserName(item.get("cUserName")!=null?item.get("cUserName").toString():null);//运营人姓名
            entity.setCDeptName(item.get("cDeptName")!=null?item.get("cDeptName").toString():null);//运营组别，所属部门
            entity.setPCUser(item.get("pCUser")!=null?item.get("pCUser").toString():null);//上级运营人工号
            entity.setPCUserName(item.get("pCUserName")!=null?item.get("pCUserName").toString():null);;//上级运营人姓名
            entity.setPCDeptName(item.get("pCDeptName")!=null?item.get("pCDeptName").toString():null);//运营组别上级，所属部门上级
            //entity.setShopName(item.get("shopName")!=null?item.get("shopName").toString():null);//店铺名称
            entity.setRegionName(item.get("regionName")!=null?item.get("regionName").toString():null);//店铺区域
            entity.setFirstSaleDay(item.get("firstSaleDay")!=null&&!item.get("firstSaleDay").equals("")?item.get("firstSaleDay").toString():null);//开售日期
			entity.setOrgName(item.get("orgName")!=null?item.get("orgName").toString():null);//机构名称
        }

		entity.setVGsBm(vGsBm);
		entity.setInfoTime(agoDay);//统计的时间
		entity.setGrowthRate(growthRate);//日达成率
		entity.setAccumulateOrder(accumulateOrder);//累计订单数
		entity.setTodayOrder(todayOrder);//当日订单数
		entity.setTodayAmount(todayAmount);//当日订单金额
		entity.setAccumulateAmount(accumulateAmount);//累计订单金额
		entity.setTimeSchedule( timeSchedule);//时间进度
		entity.setProductType(addType);//类型：0全部，1精品
		entity.setTodayAmountLocal(todayAmountLocal);//当日订单金额(原货币)
		entity.setAccumulateAmountLocal(todayAmountLocallateAmount);//累计订单金额(原货币)

		return entity;
	}

	@Override
	public int delByDay(String agoDay) {
		int result = diySqlMapper.delTpAnalysisDailyTargetByInfoTime(agoDay);
		return result;
	}


}
